package drds.global_transaction.api.message_codec.request_and_response.transaction.global_transaction.global_transaction_lock_record_ids_check;

import java.nio.ByteBuffer;

import drds.global_transaction.api.api.RpcContext;
import drds.global_transaction.api.message_codec.IMergedMessage;
import drds.global_transaction.api.message_codec.request_and_response.transaction.TransactionResponse;
import drds.global_transaction.api.message_codec.request_and_response.transaction.global_transaction.branch_transaction_register.BranchTransactionRegisterRequestMessage;
import lombok.Getter;
import lombok.Setter;

public class GlobalTransactionLockRecordIdsCheckRequestMessage extends BranchTransactionRegisterRequestMessage implements IMergedMessage
{

	private static final long serialVersionUID = 1242711598812634704L;
	@Setter
	@Getter
	private long globalTransactionId;
	@Setter
	@Getter
	private String resourceId;
	@Setter
	@Getter
	private String tableNameAndLockRecordIdsStringsString;

	@Override
	public short getTypeCode()
	{
		return global_transaction_lock_record_ids_check_request_message;
	}

	@Override
	public byte[] encode()
	{
		byte[] lockKeyBytes = null;
		if (this.tableNameAndLockRecordIdsStringsString != null)
		{
			lockKeyBytes = tableNameAndLockRecordIdsStringsString.getBytes(UTF8);
			if (lockKeyBytes.length > 512)
			{
				byteBuffer = ByteBuffer.allocate(lockKeyBytes.length + 1024);
			}
		}

		// 1. Transaction Id
		byteBuffer.putLong(this.globalTransactionId);
		// 2. Branch Type
//        byteBuffer.map$channelToRpcContextMap((byte) this.branchType.ordinal());
		// 3. Resource Id
		if (this.resourceId != null)
		{
			byte[] bytes = resourceId.getBytes(UTF8);
			byteBuffer.putShort((short) bytes.length);
			if (bytes.length > 0)
			{
				byteBuffer.put(bytes);
			}
		} else
		{
			byteBuffer.putShort((short) 0);
		}

		// 4. Lock Key
		if (this.tableNameAndLockRecordIdsStringsString != null)
		{
			byteBuffer.putInt(lockKeyBytes.length);
			if (lockKeyBytes.length > 0)
			{
				byteBuffer.put(lockKeyBytes);
			}
		} else
		{
			byteBuffer.putInt(0);
		}

		byteBuffer.flip();
		byte[] bytes = new byte[byteBuffer.limit()];
		byteBuffer.get(bytes);
		return bytes;
	}

	@Override
	public void decode(ByteBuffer byteBuffer)
	{
		this.globalTransactionId = byteBuffer.getLong();
		// this.branchType = BranchType.get(byteBuffer.get());
		short resourceIdLength = byteBuffer.getShort();
		if (resourceIdLength > 0)
		{
			byte[] bytes = new byte[resourceIdLength];
			byteBuffer.get(bytes);
			this.setResourceId(new String(bytes, UTF8));
		}

		int lockKeyLength = byteBuffer.getInt();
		if (lockKeyLength > 0)
		{
			byte[] bytes = new byte[lockKeyLength];
			byteBuffer.get(bytes);
			this.setTableNameAndLockRecordIdsStringsString(new String(bytes, UTF8));
		}
	}

	@Override
	public TransactionResponse handle(RpcContext rpcContext)
	{
		return transactionCoordinatorInboundHandler.handle(rpcContext, this);
	}

}
